package internal

import (
	"context"
	"errors"
	"k9-panel/app/model"
	"k9-panel/app/query"
	"k9-panel/app/service/dto"
)

type AccountService struct {
}

func (a *AccountService) Delete(ctx context.Context, param *dto.AccountDeleteParam) (uint, error) {
	info, err := query.Account.
		Where(query.Account.Username.Eq(param.Username)).Limit(1).Delete()
	if err != nil {
		return 0, err
	}
	return uint(info.RowsAffected), nil
}

func (a *AccountService) List() ([]*model.Account, error) {
	return query.Account.Find()
}

func (a *AccountService) Update(ctx context.Context, param *dto.AccountCreateParam) (uint, error) {
	account, err := a.Query(ctx, &dto.AccountQueryParam{
		Username: param.Username,
	})
	if err != nil || account == nil {
		return 0, errors.New("用户或密码错误！")
	}
	loginAccount := model.Account{
		Username: param.Username,
		Password: param.OldPassword,
		Salt:     account.Salt,
	}
	same, _ := loginAccount.Same(account.Password)
	if !same {
		return 0, errors.New("用户或密码错误！")
	}
	update2 := model.Account{
		Username: param.Username,
		Password: param.Password,
		Salt:     account.Salt,
	}

	items := model.Account{Password: update2.Hash2()}
	aff, err := query.Account.Where(query.Account.Username.Eq(param.Username)).Updates(items)
	if err != nil {
		return 0, err
	}
	return uint(aff.RowsAffected), err
}

func (a *AccountService) UpdateOtherPassword(ctx context.Context, param *dto.AccountCreateParam) (uint, error) {
	account, err := a.Query(ctx, &dto.AccountQueryParam{
		Username: param.Username,
	})
	if err != nil || account == nil {
		return 0, errors.New("用户或密码错误！")
	}

	update2 := model.Account{
		Username: param.Username,
		Password: param.Password,
		Salt:     account.Salt,
	}

	items := model.Account{Password: update2.Hash2()}
	aff, err := query.Account.Where(query.Account.Username.Eq(param.Username)).Updates(items)
	if err != nil {
		return 0, err
	}
	return uint(aff.RowsAffected), err
}
func (a *AccountService) Get(ctx context.Context, id uint) (*model.Account, error) {
	//TODO implement me
	return query.Account.Where(query.Account.ID.Eq(id)).First()
}

func (a *AccountService) Create(ctx context.Context, param *model.Account) (uint, error) {
	err := query.Account.Create(param)
	if err != nil {
		return 0, err
	}
	return param.ID, nil
}

func (a *AccountService) Query(ctx context.Context, param *dto.AccountQueryParam) (*model.Account, error) {
	return query.Account.ReadDB().Where(query.Account.Username.Eq(param.Username)).First()
}
